// pages/student/kaoshi/kaoshi.js
Page({
  data: {
    examList: [],
    isLoading: true,
    tabs: ['全部考试', '即将考试', '已完成'],
    activeTab: 0
  },

  onLoad: function() {
    this.loadExams();
  },

  onPullDownRefresh: function() {
    this.loadExams().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  switchTab: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ activeTab: index });
    this.loadExams();
  },

  loadExams: function() {
    this.setData({ isLoading: true });
    
    const status = this.data.activeTab === 1 ? 'upcoming' : 
                  this.data.activeTab === 2 ? 'completed' : '';
    
    return new Promise((resolve) => {
      wx.request({
        // 修改请求地址为正确的路由
        url: 'http://localhost:3000/api/exams/student',
        method: 'GET',
        data: { status },
        header: {
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const examList = res.data.map(exam => ({
              ...exam,
              examTime: exam.examTime ? exam.examTime.slice(0, 5) : ''
            }));
            
            this.setData({
              examList,
              isLoading: false
            });
          } else {
            wx.showToast({
              title: '获取考试安排失败',
              icon: 'none'
            });
            this.setData({ isLoading: false });
          }
          resolve();
        },
        fail: (err) => {
          console.error('请求失败:', err);
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
          this.setData({ isLoading: false });
          resolve();
        }
      });
    });
  },

  viewExamDetail: function(e) {
    const examId = e.currentTarget.dataset.id;
    // 跳转到考试详情页面
    wx.navigateTo({
      url: `/pages/student/kaoshi/detail?id=${examId}`
    });
  },

  addToCalendar: function(e) {
    const examId = e.currentTarget.dataset.id;
    const exam = this.data.examList.find(item => item.id === examId);
    
    wx.showModal({
      title: '添加到日历',
      content: '是否将该考试安排添加到系统日历？',
      success: (res) => {
        if (res.confirm) {
          // 实现添加到日历的功能
          wx.showToast({
            title: '已添加到日历',
            icon: 'success'
          });
        }
      }
    });
  }
});